//
//  ZBXMPagePageView.swift
//  zhiboxiangmu
//
//  Created by 丁鼎 on 2017/7/4.
//  Copyright © 2017年 丁鼎. All rights reserved.
//

import UIKit


private let kContentCollectionViewCellID = "kContentCollectionViewCellID"

protocol ZBXMContentViewdelegate : class  {
    func contentView(_ contentView : ZBXMContentView , didEndScrollew index : Int)
    func contentView(_ contentView : ZBXMContentView , startIndex : Int , targetIndex : Int,progress : CGFloat)
}

class ZBXMContentView: UIView {

    
    weak var delegate : ZBXMContentViewdelegate?
    fileprivate var childVcs: [UIViewController]
    fileprivate var parentVc :UIViewController
    fileprivate var startOffsetX : CGFloat = 0
    fileprivate var  isForbidDelegate : Bool = false
    fileprivate lazy var collectionview : UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = self.bounds.size
        layout.scrollDirection = UICollectionViewScrollDirection.horizontal
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        
        let collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: layout)
        
        
        collectionView.delegate = self
        collectionView.isPagingEnabled = true
        collectionView.dataSource = self
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kContentCollectionViewCellID)
        collectionView.bounces = false
        return collectionView;
    }()
    
    
    init(frame: CGRect,childVcs:[UIViewController],parentVc :UIViewController) {
        self.childVcs = childVcs;
        self.parentVc = parentVc
        super .init(frame: frame)

        SetUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
 
    }


}


extension ZBXMContentView
{
    fileprivate func SetUpUI(){
        //1,将childVc中的控制器添加到parentVc
        for childVc in childVcs {
            parentVc.addChildViewController(childVc)
        }
 
        addSubview(collectionview)
        
    }
  
}

//数据源方法
extension ZBXMContentView :UICollectionViewDataSource
{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return childVcs.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell  = collectionView.dequeueReusableCell(withReuseIdentifier:kContentCollectionViewCellID, for: indexPath)
        cell.backgroundColor = UIColor.randomColor()
        
        for subview  in cell.contentView.subviews {
            subview .removeFromSuperview()
        }
        
        let childvc = childVcs[indexPath.row]
        cell.contentView .addSubview(childvc.view)
        
        return cell
    }

}

//代理方法
extension ZBXMContentView: UICollectionViewDelegate
{
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate{
            
            scrolleviewdidEndScroll()
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        scrolleviewdidEndScroll()
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        isForbidDelegate = false
        startOffsetX = scrollView.contentOffset.x
    }
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let  contentOffsetX = scrollView.contentOffset.x
        
        guard  contentOffsetX != startOffsetX && !isForbidDelegate else {
            return
        }
        
        //1,定义参数
        var sourceIndex = 0
        var targetIndex = 0
        var progress : CGFloat = 0
        
        //2,获取参数
        let collectionWidth = collectionview.bounds.width
        if contentOffsetX > startOffsetX{ //左划
            sourceIndex = Int(contentOffsetX/collectionWidth)
            targetIndex = sourceIndex + 1
            if targetIndex >= childVcs.count 
            {
                targetIndex = childVcs.count - 1
            }
            
            progress = (contentOffsetX - startOffsetX) / collectionWidth
            
            if((contentOffsetX - startOffsetX) == collectionWidth)
            {
                targetIndex = sourceIndex
            }
            
        }else{//右滑
            
            targetIndex = Int(contentOffsetX/collectionWidth)
            sourceIndex = targetIndex + 1

            progress = (startOffsetX - contentOffsetX) / collectionWidth
            
        }
        
        
        
        delegate?.contentView(self, startIndex: sourceIndex, targetIndex: targetIndex , progress: progress)
    }
    
    
    private func scrolleviewdidEndScroll(){
        let index = Int(collectionview.contentOffset.x / collectionview.bounds.width)
       delegate?.contentView(self, didEndScrollew: index)
        
    }
    
    
    
}

//遵守ZBXMTitleView协议
extension ZBXMContentView : ZBXMTitleViewDelegate
{
    func titleView(_ titleView: ZBXMTitleView, targetIndex: Int) {
        isForbidDelegate = true
        
        let indexPath = IndexPath(item: targetIndex, section: 0)
        collectionview.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
    }
}




